package com.tsp_tux.demo.Controller;

import com.tsp_tux.demo.Dao.*;
import com.tsp_tux.demo.Entity.*;
import com.tsp_tux.demo.Service.ArticleService;
import com.tsp_tux.demo.Util.easyRespBean;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author 沈育洋
 */
@RestController
@CrossOrigin
public class ArticleController {


    @Resource
    ArticleService articleService;

    @Resource
    ArticleRepository articleRepository;

    /**
     * 根据uid拿最新的三篇文章
     * @param uid 学号/工号
     * @return 返回最新的三篇
     */
    @GetMapping("/getTop3")
    public RespBean getTop3(@RequestParam("uid")String uid){
        return articleService.getTop3Articles(uid);
    }

    @GetMapping(value = "article")
    public RespBean getArticle(Integer aid) {
        List<ArticleContent_List> articleContent_lists = articleService.getArticleByAid(aid);
        if (articleContent_lists.isEmpty()) {
            return easyRespBean.noFound();
        }
        return easyRespBean.ok(articleContent_lists);
    }

    @PostMapping(value = "search")
    public RespBean search(String search) {
        return articleService.searchArticle(search);
    }

    /**
     * @param uid   String 用户ID
     * @param state int 文章状态
     * @return 按照用户id和文章状态查找文章
     * @author 周志伟
     */
    @RequestMapping(value = "/getSpecArticle", method = RequestMethod.GET)
    @ResponseBody
    public RespBean getArticleByStateByUidAndState(String uid, int state) {
        List<Article_List> article_Lists = articleService.getArticleByStateByUidAndState(uid, state);
        if (article_Lists.isEmpty()) {
            return easyRespBean.noFound();
        }
        return easyRespBean.ok(article_Lists);
    }

    /**
     * @author 周志伟
     * @param uid 用户id
     * @param sid 专题id
     * @return article_List
     */
    @RequestMapping(value = "/checkSpecBlog", method = RequestMethod.GET)
    @ResponseBody
    public RespBean getArticleByStateByUidAndSid(String uid, int sid) {
        List<Article_List> article_Lists = articleService.getArticleByStateByUidAndSid(uid, sid);
        if (article_Lists.isEmpty()) {
            return easyRespBean.noFound();
        }
        return easyRespBean.ok(article_Lists);
    }

    /**
     *
     * @param state  int	0-根据用户名查询；1-根据专题名查询
     * @param content  	string	搜索的内容(精确搜索)
     * @return
     */
    @RequestMapping(value="/searchBlog", method = RequestMethod.POST)
    @ResponseBody
    public RespBean SearchBlog(String content, int state) {
        if (state == 0)   // 0-根据用户名查询
        {
            List<Article_List> article_Lists = articleService.getArticleByStateByUsername(content);
            if (article_Lists.isEmpty()) {
                return easyRespBean.noFound();
            }
            return easyRespBean.ok(article_Lists);
        }
        if (state == 1)    //1-根据专题名查询
        {
            List<Article_List> article_Lists = articleService.getArticleByStateBySubname(content);
            if (article_Lists.isEmpty()) {
                return easyRespBean.noFound();
            }
            return easyRespBean.ok(article_Lists);
        }
        return new RespBean(500, "查询失败!", null);

    }

    /**
     * @param aid int 文章ID
     * @return 返回评论
     * @author 周志伟
     */
    @RequestMapping(value = "/getComments", method = RequestMethod.GET)
    @ResponseBody
    public RespBean getComments(Integer aid) {
        List<Comments_List> comments_Lists = articleService.getComments(aid);
        if (comments_Lists.isEmpty()) {
            return easyRespBean.noFound();
        }
        return easyRespBean.ok(comments_Lists);
    }

    /**
     * @param aid      int    文章id
     * @param content  String 评论内容
     * @param parentId String 父评论id，没有则为-1
     * @param uid      string 用户id
     * @param puid     String 被评论人的id
     * @return RespBean
     * @author 周志伟
     */
    @RequestMapping(value = "/comment", method = RequestMethod.POST)
    @ResponseBody
    public RespBean PreserveComment(Integer aid, String content, Integer parentId, String uid, String puid) {

        int result = articleService.PreserveComment(aid, content, parentId, uid, puid);
        if (result == 0)
            return new RespBean(200, "Success!", null);
        else
            return new RespBean(500, "Preserve Failed!", null);

    }

    /**
     * @param aid int 文章ID
     * @param uid String 用户ID
     * @param opt int 操作 0 点赞或 1 收藏
     * @return RespBean
     * @author 周志伟
     */
    @PostMapping("/pcOption")
    @ResponseBody
    public RespBean ArticleAndUser(Integer aid, String uid, int opt) {
        if (opt == 0)   // 点赞
        {
            int result = articleService.ArticleAndUserPraise(aid, uid);
            if (result == 0) {
                return easyRespBean.okWithMsg("点赞成功");
            } else {
                if (result == 2) {
                    return easyRespBean.okWithMsg("取消点赞成功！");
                }
            }
        }
        if (opt == 1)    //收藏
        {
            int result = articleService.ArticleAndUserCollect(aid, uid);
            if (result == 0)
                return new RespBean(200, "收藏成功", null);
            else {
                if (result == 2)
                    return new RespBean(200, "取消收藏成功！", null);
            }

        }
        return new RespBean(500, "点赞或收藏失败!", null);

    }

    /**
     * @param aid int 文章ID
     * @return RespBean
     * @author 周志伟
     */
    @GetMapping("/getDigital")
    @ResponseBody
    public RespBean getDigital(Integer aid) {
        PraiseAndCollectNum praiseAndCollefctNum = articleService.getDigital(aid);
        return new RespBean(200, "Success!", praiseAndCollefctNum);
    }

    /**
     * 创建/发布/存草稿 文章
     *
     * @param uid:String       用户id
     * @param aid:int          （可空）文章id
     * @param title:Stinrg     文章标题
     * @param mdContent:String 文章内容的markdown编码
     * @param summary:String   （可空）文章摘要
     * @param sid:int          （可空）隶属专题id
     * @param state:int        隶属专题id 当前文章状态
     * @param tags:String[]    （可空）文章所含标签的数组
     * @param original:int     （可空）0原创，1转载
     * @param atype:int         （可空）文章类型，0学生分享，1学生作业，-1（默认）其他
     * @return 添加结果信息
     *
     * @author 张志豪
     */
    @PostMapping("/creatArticle")
    @CrossOrigin
    public RespBean creatArticle(@RequestParam(value = "uid") String uid,
                                 @RequestParam(value = "aid", defaultValue = "-1") int aid,
                                 @RequestParam(value = "title") String title,
                                 @RequestParam(value = "mdContent") String mdContent,
                                 @RequestParam(value = "summary", defaultValue = "") String summary,
                                 @RequestParam(value = "sid", defaultValue = "-1") int sid,
                                 @RequestParam(value = "state") int state,
                                 @RequestParam(value = "tags", defaultValue = "") String[] tags,
                                 @RequestParam(value = "original",defaultValue = "1") int original,
                                 @RequestParam(value = "atype",defaultValue = "0")int atype) {
        return articleService.creatArticle(uid, aid, title, mdContent, summary, sid, state, tags,original,atype);
    }

    /**
     * 获取我的收藏
     *
     * @author 张志豪
     * @param uid uid
     * @return 数组
     */
    @GetMapping("/myCollect")
    @CrossOrigin
    public RespBean getMyCollect(@RequestParam("uid") String uid) {
        return articleService.getMyCollect(uid);
    }

    /**
     * @param aid 文章id
     * @return 按照用户id和文章状态查找文章
     * @author 周志伟
     */
    @RequestMapping(value = "/getBlog", method = RequestMethod.GET)
    @ResponseBody
    public RespBean getArticleByAid(Integer aid) {
        List<ArticleContent_List> article_Lists = articleService.getArticleByAid(aid);
        if (article_Lists.isEmpty()) {
            return new RespBean(404, "Not Found!", null);
        }
        return new RespBean(200, "Success!", article_Lists);
    }

    /**
     *
     * @return 前端发送请求，后端返回8条已发布的推荐文章信息（点赞数最高
     * @author 张帅
     */
    @GetMapping("/getCommendArticle")
    @ResponseBody
    @CrossOrigin
    public RespBean getCommendArtical(){
        List<Article_List_1> articals=articleService.getCommendArtical1();
        return  new RespBean(200,"success",articals);
    }

    /**
     * @param aid int 文章ID
     * @return 删除文章，修改文章状态，返回状态信息
     * @author 童一凡
     */
    @RequestMapping("/deleteArticle")
    @ResponseBody
    public RespBean deleteArticle(Integer aid){
        Article deletearticle=articleRepository.findByAid(aid);
        int state_str =deletearticle.getState();
        if (state_str != 0 && state_str != 1) {
            return new RespBean(403, "文章不存在", 0);
        }else
            articleService.deleteArticle(aid);
        return new RespBean(200,"删除成功",1);
    }

    /**
     * @param keyword String 关键字
     * @return 搜索文章，返回文章信息
     * @author 童一凡
     */
    @PostMapping("/searchArticle")
    @ResponseBody
    @CrossOrigin
    public RespBean searchArticle(String keyword){
        String[] str=keyword.split(" ");
        List<String> aid=new ArrayList<>();
        for(int i=0;i<str.length;i++){
            List<String> search_Key=articleService.searchArticleByKeyword(str[i]);
            if(search_Key!=null&& !search_Key.isEmpty()){
                aid.addAll(search_Key);
            }
        }
        if( aid==null||aid.size()==0){
            return new RespBean(404, "文章不存在", null);
        }
        else {
            HashMap<String, Integer> hMap = new HashMap<>();
            for (String str1 : aid) {
                if (hMap.get(str1) == null) {
                    hMap.put(str1, 1);
                } else {
                    hMap.put(str1, hMap.get(str1) + 1);
                }
            }
            HashMap<String, Integer> finalOut = new LinkedHashMap<>();
            hMap.entrySet()
                    .stream()
                    .sorted((p1, p2) -> p2.getValue().compareTo(p1.getValue()))
                    .collect(Collectors.toList()).forEach(ele -> finalOut.put(ele.getKey(), ele.getValue()));
            List<String> str2 = new ArrayList<String>();
            for (Map.Entry<String, Integer> str3 : finalOut.entrySet()) {
                str2.add(str3.getKey());
            }
            List<Article_List_1> search_list = new ArrayList<>();
            for (int i = 0; i < str2.size(); i++) {
                Article_List_1 search_List = articleService.searchArticleByKeyword2(str2.get(i));
                search_list.add(search_List);
            }
            if (search_list.isEmpty()) {
                return new RespBean(404, "文章不存在", null);
            } else
                return new RespBean(200, "Success!", search_list);
        }
    }

    /**
     * @param aid int 文章ID
     * @param uid String 用户ID
     * @return 返回是否点赞或收藏
     * @author 周志伟
     */
    @GetMapping("/cpConfirm")
    @ResponseBody
    public RespBean getArticlePraiseCollectState(Integer aid, String uid) {

            int result_1 = articleService.getArticleAndUserPraiseState(aid, uid);
            int result_2 = articleService.getArticleAndUserCollectState(aid, uid);
            if(result_1==2||result_2==2)
                return new RespBean(500, "查询失败!", null);
            else
                return new RespBean(200, "查询成功!", new isPraiseAndCollect(result_2,result_1));

    }

        /**
     * @param aid int 文章ID
     * @return 修改文章状态并返回状态信息
     * @author 谢颖
     */
    @RequestMapping("/rebuildArticle")
    @ResponseBody
    public RespBean rebuildArticle(Integer aid,int state) {
        if (aid == -1) {
            return new RespBean(500, "文章状态错误", null);
        } else {
            Article rebuildArticle = articleRepository.findByAid(aid);
            state=0;
            int state_str = rebuildArticle.getState();
            if (state_str != 0 && state_str != 1) {
                return new RespBean(403, "修改失败", 0);
            } else
                articleService.rebuildArticle(aid);
            return new RespBean(200, "修改成功", 1);
        }
    }

    /**
     * 文章评分
     * @author 张志豪
     *
     * @param aid 文章id
     * @param uid 评分用户id
     * @param mark 分数
     * @return 执行结果信息
     */
    @PostMapping("mark")
    public RespBean markArticle(@RequestParam("aid")int aid,
                                @RequestParam("uid")String uid,
                                @RequestParam("mark")float mark){
        return articleService.evaluateArticle(aid, uid, mark);
    }

    /**
     * 单独获取文章评分
     * @author 张志豪
     *
     * @param aid 文章id
     * @return 获取结果
     */
    @GetMapping("checkScore")
    public RespBean getArticleScore(@RequestParam("aid")int aid){
        Article_Evalue article_evalue = articleService.getArticleMarkByAid(aid);
        if(article_evalue.getMark() == null)
            return easyRespBean.ok("文章还未评分。",null);
        return easyRespBean.ok("查询文章评分成功",article_evalue);
    }

    @GetMapping("/getHighest3")
    public RespBean getHighest3(@RequestParam("uid")String uid){
        return articleService.getHighest3(uid);
    }
    /**
     *
     * @author 周志伟
     *
     * @param uid 用户id
     * @return 获取返回该学生所参加专题内打分人数最少且未打分过的五篇文章
     */
    @GetMapping("/fiveMark")
    public RespBean getFiveMark(@RequestParam("uid") String uid){
        List<Article_List_2> article_Lists = articleService.getFiveMark(uid);
        if (article_Lists.isEmpty()) {
            return new RespBean(404, "Not Found!", null);
        }
        return new RespBean(200, "Success!", article_Lists);
    }

    /**
     * 获取用户对文章的评分
     * @author 张志豪
     */
    @GetMapping("checkArticleScore")
    public RespBean checkArticleScore(@RequestParam("uid")String uid,
                                      @RequestParam("aid")int aid){
        return articleService.checkArticleScore(uid,aid);
    }

    /**
     * 获取每日文章数
     * @author 周志伟
     */
    @GetMapping("/getDailyNum")
    public RespBean getDailyNum(){
        List<DailyStatistics> dailyStatistics = articleService.getDailyNum();
        if (dailyStatistics.isEmpty()) {
            return new RespBean(404, "Not Found!", null);
        }
        return new RespBean(200, "Success!", dailyStatistics);
    }





}
